package me.leiusual.sharing.repository.datasource

import androidx.lifecycle.MutableLiveData
import androidx.paging.PageKeyedDataSource
import io.reactivex.observers.DisposableSingleObserver
import me.leiusual.sharing.api.ApiSharing
import me.leiusual.sharing.api.model.orderlist.Content
import me.leiusual.sharing.api.model.orderlist.OrderList
import me.leiusual.sharing.repository.model.Data
import timber.log.Timber

/**
 * author: leiusual
 * create on: 2019-07-31
 * description:
 */
class OrderDataSource(
    private val apiSharing: ApiSharing,
    private val storeId: Long,
    private val keyword: String,
    private val status: Int
) : PageKeyedDataSource<Int, Content>() {

  val loadInitial = MutableLiveData<Data<OrderList>>()

  override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Content>) {
    if (storeId == 0L) {
      apiSharing.orderList(0, params.requestedLoadSize, keyword, status)
    } else {
      apiSharing.orderList(storeId, 0, params.requestedLoadSize, keyword, status)
    }
        .subscribe(object : DisposableSingleObserver<OrderList>() {

          override fun onStart() {
            loadInitial.postValue(Data.Loading())
          }

          override fun onError(e: Throwable) {
            loadInitial.postValue(Data.Error(e))
            Timber.w(e)
          }

          override fun onSuccess(t: OrderList) {
            loadInitial.postValue(Data.Success(t))
            callback.onResult(t.model.content, null, 1)
          }
        })
  }

  override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Content>) {
    // ignore
  }

  override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Content>) {
    if (storeId == 0L) {
      apiSharing.orderList(params.key, params.requestedLoadSize, keyword, status)
    } else {
      apiSharing.orderList(storeId, params.key, params.requestedLoadSize, keyword, status)
    }
        .subscribe(object : DisposableSingleObserver<OrderList>() {

          override fun onError(e: Throwable) {
            Timber.w(e)
          }

          override fun onSuccess(t: OrderList) {
            val list = t.model.content
            callback.onResult(list, if (list.size == params.requestedLoadSize) params.key + 1 else null)
          }
        })
  }
}